
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import json
from ozon_client import OzonClient

class OzonApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Ozon API 客户端")
        self.root.geometry("900x600")

        # 从apikey_info.txt文件读取API凭证
        try:
            with open("apikey_info.txt", "r") as f:
                lines = f.readlines()
                for line in lines:
                    if line.startswith("clientid:"):
                        client_id = line.split(":")[1].strip()
                    elif line.startswith("apikey:"):
                        api_token = line.split(":")[1].strip()
        except FileNotFoundError:
            client_id = None
            api_token = None
            messagebox.showwarning("警告", "未找到apikey_info.txt文件，请在设置页面手动配置API凭证")
        except Exception as e:
            client_id = None
            api_token = None
            messagebox.showerror("错误", f"读取apikey_info.txt文件时出错: {str(e)}")

        # 初始化Ozon客户端
        self.client = OzonClient(client_id, api_token)

        # 创建选项卡控件
        self.tab_control = ttk.Notebook(root)

        # 创建各个选项卡
        self.settings_tab = ttk.Frame(self.tab_control)
        self.company_tab = ttk.Frame(self.tab_control)
        self.shop_tab = ttk.Frame(self.tab_control)
        self.products_tab = ttk.Frame(self.tab_control)
        self.price_stock_tab = ttk.Frame(self.tab_control)
        self.upload_tab = ttk.Frame(self.tab_control)

        # 添加选项卡到控件
        self.tab_control.add(self.settings_tab, text='设置')
        self.tab_control.add(self.company_tab, text='商家信息')
        self.tab_control.add(self.shop_tab, text='店铺信息')
        self.tab_control.add(self.products_tab, text='商品信息')
        self.tab_control.add(self.price_stock_tab, text='价格库存')
        self.tab_control.add(self.upload_tab, text='上架产品')

        self.tab_control.pack(expand=1, fill="both")

        # 初始化各个选项卡的内容
        self.init_settings_tab()
        self.init_company_tab()
        self.init_shop_tab()
        self.init_products_tab()
        self.init_price_stock_tab()
        self.init_upload_tab()

    def init_settings_tab(self):
        """初始化设置选项卡"""
        frame = ttk.Frame(self.settings_tab, padding="10")
        frame.pack(fill=tk.BOTH, expand=True)

        # API凭证输入
        ttk.Label(frame, text="Client ID:").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.client_id_entry = ttk.Entry(frame, width=40)
        self.client_id_entry.grid(row=0, column=1, pady=5, padx=10)

        ttk.Label(frame, text="API Token:").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.api_token_entry = ttk.Entry(frame, width=40, show="*")
        self.api_token_entry.grid(row=1, column=1, pady=5, padx=10)

        # 如果已从文件中读取API凭证，则显示在输入框中
        if hasattr(self, 'client') and self.client.client_id:
            self.client_id_entry.insert(0, self.client.client_id)
        if hasattr(self, 'client') and self.client.api_token:
            self.api_token_entry.insert(0, self.client.api_token)

        # 保存按钮
        save_btn = ttk.Button(frame, text="保存设置", command=self.save_settings)
        save_btn.grid(row=2, column=1, pady=10, sticky=tk.E)

    def init_company_tab(self):
        """初始化商家信息选项卡"""
        frame = ttk.Frame(self.company_tab, padding="10")
        frame.pack(fill=tk.BOTH, expand=True)

        # 获取商家信息按钮
        get_btn = ttk.Button(frame, text="获取商家信息", command=self.get_company_info)
        get_btn.pack(pady=10)

        # 商家信息显示区域
        self.company_info_text = scrolledtext.ScrolledText(frame, wrap=tk.WORD, width=80, height=20)
        self.company_info_text.pack(fill=tk.BOTH, expand=True)

    def init_shop_tab(self):
        """初始化店铺信息选项卡"""
        frame = ttk.Frame(self.shop_tab, padding="10")
        frame.pack(fill=tk.BOTH, expand=True)

        # 获取店铺信息按钮
        get_btn = ttk.Button(frame, text="获取店铺信息", command=self.get_shop_info)
        get_btn.pack(pady=10)

        # 店铺信息显示区域
        self.shop_info_text = scrolledtext.ScrolledText(frame, wrap=tk.WORD, width=80, height=20)
        self.shop_info_text.pack(fill=tk.BOTH, expand=True)

    def init_products_tab(self):
        """初始化商品信息选项卡"""
        frame = ttk.Frame(self.products_tab, padding="10")
        frame.pack(fill=tk.BOTH, expand=True)

        # 商品列表控件
        self.products_tree = ttk.Treeview(frame, columns=("id", "name", "price", "status"), show="headings")
        self.products_tree.heading("id", text="商品ID")
        self.products_tree.heading("name", text="货号")
        self.products_tree.heading("price", text="价格")
        self.products_tree.heading("status", text="状态")

        self.products_tree.column("id", width=80)
        self.products_tree.column("name", width=300)
        self.products_tree.column("price", width=100)
        self.products_tree.column("status", width=100)

        self.products_tree.pack(fill=tk.BOTH, expand=True)

        # 按钮框架
        btn_frame = ttk.Frame(frame)
        btn_frame.pack(fill=tk.X, pady=10)

        # 获取商品列表按钮
        get_btn = ttk.Button(btn_frame, text="获取商品列表", command=self.get_products)
        get_btn.pack(side=tk.LEFT, padx=5)

        # 刷新按钮
        refresh_btn = ttk.Button(btn_frame, text="刷新", command=self.refresh_products)
        refresh_btn.pack(side=tk.LEFT, padx=5)

    def init_price_stock_tab(self):
        """初始化价格库存选项卡"""
        frame = ttk.Frame(self.price_stock_tab, padding="10")
        frame.pack(fill=tk.BOTH, expand=True)

        # 输入框框架
        input_frame = ttk.LabelFrame(frame, text="商品筛选", padding="10")
        input_frame.pack(fill=tk.X, pady=5)

        # 商品ID输入
        ttk.Label(input_frame, text="商品ID:").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.price_stock_product_id_entry = ttk.Entry(input_frame, width=30)
        self.price_stock_product_id_entry.grid(row=0, column=1, pady=5, padx=10)

        # 商品货号输入
        ttk.Label(input_frame, text="商品货号:").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.price_stock_offer_id_entry = ttk.Entry(input_frame, width=30)
        self.price_stock_offer_id_entry.grid(row=1, column=1, pady=5, padx=10)

        # 按钮框架
        btn_frame = ttk.Frame(input_frame)
        btn_frame.grid(row=2, column=1, pady=10, sticky=tk.W)

        # 获取价格按钮
        get_prices_btn = ttk.Button(btn_frame, text="获取价格", command=self.get_product_prices)
        get_prices_btn.pack(side=tk.LEFT, padx=5)

        # 获取库存按钮
        get_stocks_btn = ttk.Button(btn_frame, text="获取库存", command=self.get_product_stocks)
        get_stocks_btn.pack(side=tk.LEFT, padx=5)

        # 获取全部按钮
        get_all_btn = ttk.Button(btn_frame, text="获取全部", command=self.get_all_price_stock)
        get_all_btn.pack(side=tk.LEFT, padx=5)

        # 价格和库存显示区域
        notebook = ttk.Notebook(frame)
        notebook.pack(fill=tk.BOTH, expand=True, pady=10)

        # 价格选项卡
        prices_frame = ttk.Frame(notebook)
        notebook.add(prices_frame, text='价格信息')

        # 价格列表控件
        self.prices_tree = ttk.Treeview(prices_frame, columns=("product_id", "offer_id", "price", "old_price", "premium_price"), show="headings")
        self.prices_tree.heading("product_id", text="商品ID")
        self.prices_tree.heading("offer_id", text="货号")
        self.prices_tree.heading("price", text="价格")
        self.prices_tree.heading("old_price", text="原价")
        self.prices_tree.heading("premium_price", text="高级价格")

        self.prices_tree.column("product_id", width=80)
        self.prices_tree.column("offer_id", width=200)
        self.prices_tree.column("price", width=100)
        self.prices_tree.column("old_price", width=100)
        self.prices_tree.column("premium_price", width=100)

        self.prices_tree.pack(fill=tk.BOTH, expand=True)

        # 库存选项卡
        stocks_frame = ttk.Frame(notebook)
        notebook.add(stocks_frame, text='库存信息')

        # 库存列表控件
        self.stocks_tree = ttk.Treeview(stocks_frame, columns=("product_id", "offer_id", "warehouse", "stock"), show="headings")
        self.stocks_tree.heading("product_id", text="商品ID")
        self.stocks_tree.heading("offer_id", text="货号")
        self.stocks_tree.heading("warehouse", text="仓库")
        self.stocks_tree.heading("stock", text="库存")

        self.stocks_tree.column("product_id", width=80)
        self.stocks_tree.column("offer_id", width=200)
        self.stocks_tree.column("warehouse", width=200)
        self.stocks_tree.column("stock", width=100)

        self.stocks_tree.pack(fill=tk.BOTH, expand=True)

    def init_upload_tab(self):
        """初始化上架产品选项卡"""
        frame = ttk.Frame(self.upload_tab, padding="10")
        frame.pack(fill=tk.BOTH, expand=True)

        # 产品信息输入表单
        form_frame = ttk.LabelFrame(frame, text="产品信息", padding="10")
        form_frame.pack(fill=tk.BOTH, expand=True)

        # 产品名称
        ttk.Label(form_frame, text="产品名称:").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.product_name_entry = ttk.Entry(form_frame, width=50)
        self.product_name_entry.grid(row=0, column=1, pady=5, padx=10)

        # 产品描述
        ttk.Label(form_frame, text="产品描述:").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.product_description_text = scrolledtext.ScrolledText(form_frame, wrap=tk.WORD, width=50, height=5)
        self.product_description_text.grid(row=1, column=1, pady=5, padx=10)

        # 价格
        ttk.Label(form_frame, text="价格:").grid(row=2, column=0, sticky=tk.W, pady=5)
        self.product_price_entry = ttk.Entry(form_frame, width=20)
        self.product_price_entry.grid(row=2, column=1, sticky=tk.W, pady=5, padx=10)

        # 库存
        ttk.Label(form_frame, text="库存数量:").grid(row=3, column=0, sticky=tk.W, pady=5)
        self.product_stock_entry = ttk.Entry(form_frame, width=20)
        self.product_stock_entry.grid(row=3, column=1, sticky=tk.W, pady=5, padx=10)

        # 上架按钮
        upload_btn = ttk.Button(frame, text="上架产品", command=self.upload_product)
        upload_btn.pack(pady=10)

        # 状态显示
        self.upload_status_text = scrolledtext.ScrolledText(frame, wrap=tk.WORD, width=80, height=10)
        self.upload_status_text.pack(fill=tk.BOTH, expand=True)

    def save_settings(self):
        """保存API设置"""
        client_id = self.client_id_entry.get()
        api_token = self.api_token_entry.get()

        if not client_id or not api_token:
            messagebox.showerror("错误", "请填写完整的API凭证")
            return

        self.client.set_credentials(client_id, api_token)
        messagebox.showinfo("成功", "API凭证已保存")

    def get_company_info(self):
        """获取商家信息"""
        if not self._check_credentials():
            return

        self.company_info_text.delete(1.0, tk.END)
        self.company_info_text.insert(tk.END, "正在获取商家信息...")

        result = self.client.get_company_info()

        self.company_info_text.delete(1.0, tk.END)
        if "error" in result:
            self.company_info_text.insert(tk.END, f"获取商家信息失败: {result['error']}")
        else:
            self.company_info_text.insert(tk.END, json.dumps(result, indent=2, ensure_ascii=False))

    def get_shop_info(self):
        """获取店铺信息"""
        if not self._check_credentials():
            return

        self.shop_info_text.delete(1.0, tk.END)
        self.shop_info_text.insert(tk.END, "正在获取店铺信息...")

        result = self.client.get_shop_info()

        self.shop_info_text.delete(1.0, tk.END)
        if "error" in result:
            self.shop_info_text.insert(tk.END, f"获取店铺信息失败: {result['error']}")
        else:
            self.shop_info_text.insert(tk.END, json.dumps(result, indent=2, ensure_ascii=False))

    def get_products(self):
        """获取商品列表"""
        if not self._check_credentials():
            print("未登录")
            return

        # 清空当前列表
        for item in self.products_tree.get_children():
            self.products_tree.delete(item)

        result = self.client.get_products()

        if "error" in result:
            messagebox.showerror("错误", f"获取商品列表失败: {result['error']}")
        else:
            for item in result.get("result", []).get("items", []):
                product_id = item.get("product_id", "")
                product_id_str = [str(product_id)]
                name = item.get("offer_id", "")
                name_str = [str(name)]
                result_price = self.client.get_product_prices(product_id_str, name_str)
                for item_price in result_price.get("items", []):
                    price_product_it = item_price.get("product_id", "")
                    if price_product_it == product_id:
                        prices = item_price.get("price", "")
                        print("匹配产品, 价格结果:", prices)
                        marketing_price = prices.get("marketing_price", "")
                        status = item.get("status", "")

                self.products_tree.insert("", tk.END, values=(product_id, name, marketing_price, status))

    def refresh_products(self):
        """刷新商品列表"""
        self.get_products()

    def upload_product(self):
        """上架新产品"""
        if not self._check_credentials():
            return

        name = self.product_name_entry.get()
        description = self.product_description_text.get(1.0, tk.END).strip()
        price = self.product_price_entry.get()
        stock = self.product_stock_entry.get()

        if not name or not description or not price or not stock:
            messagebox.showerror("错误", "请填写完整的产品信息")
            return

        try:
            price = float(price)
            stock = int(stock)
        except ValueError:
            messagebox.showerror("错误", "价格和库存必须为数字")
            return

        self.upload_status_text.delete(1.0, tk.END)
        self.upload_status_text.insert(tk.END, "正在上传产品...")

        # 构建产品数据
        product_data = {
            "items": [
                {
                    "product": {
                        "name": name,
                        "description": description
                    },
                    "price": price,
                    "stock": stock
                }
            ]
        }

        result = self.client.create_product(product_data)

        self.upload_status_text.delete(1.0, tk.END)
        if "error" in result:
            self.upload_status_text.insert(tk.END, f"上传产品失败: {result['error']}")
        else:
            self.upload_status_text.insert(tk.END, "产品上传成功!")
            self.upload_status_text.insert(tk.END, json.dumps(result, indent=2, ensure_ascii=False))

            # 清空表单
            self.product_name_entry.delete(0, tk.END)
            self.product_description_text.delete(1.0, tk.END)
            self.product_price_entry.delete(0, tk.END)
            self.product_stock_entry.delete(0, tk.END)

    def get_product_prices(self):
        """获取商品价格信息"""
        if not self._check_credentials():
            return

        # 清空当前列表
        for item in self.prices_tree.get_children():
            self.prices_tree.delete(item)

        # 获取输入的商品ID和货号
        product_id = self.price_stock_product_id_entry.get().strip()
        offer_id = self.price_stock_offer_id_entry.get().strip()

        # 构建查询参数
        product_ids = [product_id] if product_id else None
        offer_ids = [offer_id] if offer_id else None

        # 调用API获取价格信息
        result = self.client.get_product_prices(product_ids, offer_ids)

        if "error" in result:
            messagebox.showerror("错误", f"获取商品价格失败: {result['error']}")
        else:
            # 显示价格信息
            print("价格信息:")
            # for item in result.get("result", {}).get("items", []):
            for item in result.get("items", []):
                product_id = item.get("product_id", "")
                offer_id = item.get("offer_id", "")
                prices = item.get("price", "")

                price = prices.get("marketing_price", "")
                old_price = prices.get("price", "")
                premium_price = prices.get("premium_price", "")
                marketing_seller_price = prices.get("marketing_seller_price", "")
                print(f"商品ID: {product_id}, 货号: {offer_id}, 价格: {prices}, 原价: {old_price}, 高级价格: {premium_price}, 营销卖家价格: {marketing_seller_price}")

                self.prices_tree.insert("", tk.END, values=(product_id, offer_id, price, old_price, premium_price))

    def get_product_stocks(self):
        """获取商品库存信息"""
        if not self._check_credentials():
            return

        # 清空当前列表
        for item in self.stocks_tree.get_children():
            self.stocks_tree.delete(item)

        # 获取输入的商品ID和货号
        product_id = self.price_stock_product_id_entry.get().strip()
        offer_id = self.price_stock_offer_id_entry.get().strip()

        # 构建查询参数
        product_ids = [product_id] if product_id else None
        offer_ids = [offer_id] if offer_id else None

        # 调用API获取库存信息
        result = self.client.get_product_stocks(product_ids, offer_ids)

        if "error" in result:
            messagebox.showerror("错误", f"获取商品库存失败: {result['error']}")
        else:
            # 显示库存信息
            for item in result.get("items", []):
                product_id = item.get("product_id", "")
                offer_id = item.get("offer_id", "")
                
                # 遍历仓库库存
                for stock in item.get("stocks", []):
                    warehouse = stock.get("type", "")
                    stock_quantity = stock.get("present", "")
                    self.stocks_tree.insert("", tk.END, values=(product_id, offer_id, warehouse, stock_quantity))

    def get_all_price_stock(self):
        """同时获取商品价格和库存信息"""
        self.get_product_prices()
        self.get_product_stocks()

    def _check_credentials(self):
        """检查API凭证是否已设置"""
        if not self.client.client_id or not self.client.api_token:
            messagebox.showerror("错误", "请先在设置页面配置API凭证")
            return False
        return True

if __name__ == "__main__":
    root = tk.Tk()
    app = OzonApp(root)
    root.mainloop()
